//
// Created by gyc on 2023/4/24.
//
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

#include "../../common.h"

class Solution {
public:
    int getMinimumDifference(TreeNode *root) {

        stack<TreeNode *> s1{};
        TreeNode *curr = root;

        TreeNode *last = nullptr;
        int min = INT_MAX;

        while (curr != nullptr || !s1.empty()) {
            while (curr != nullptr) {
                s1.emplace(curr);
                curr = curr->left;
            }
            curr = s1.top();
            s1.pop();
            if (last == nullptr) {
                last = curr;
            } else {
                min = std::min(min, curr->val - last->val);
                last = curr;
            }
            curr = curr->right;
        }
        return min;
    }
};